package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestUrl = req.getRequestURI();
        // 获取当前访问的资源路径
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
                "/user/loginout"
        };
        //判断本次请求是否需要处理
        boolean check = check(urls, requestUrl);
        //如果不需要处理，则直接放行
        if (check) {
            filterChain.doFilter(req,resp);
            return;
        }

        //判断是否登录
        //1.获取session会话域中的对象
        HttpSession session = req.getSession();
        Long employee = (Long) session.getAttribute("employee");
        if (employee != null) {
            //已登录，放行
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(req, resp);
            return;
        }


        //1.获取session会话域中的对象
        //判断移动端用户登陆状态，如果已登陆，直接放行
        Long userId = (Long) req.getSession().getAttribute("user");
        if(userId != null) {
            //把当前登陆用户设置到本地线程中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(req, resp);
            return;
        }

        //如果未登录则返回未登录页面，通过输出流方式向客户端页面响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }



    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestUrl
     * @return
     */
    private boolean check(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match( url,requestUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
